'use client';

import { useState } from 'react';
import { removeFromCart } from '@/lib/cart';
import { useCart } from '@/contexts/CartContext';

interface ShoppingCartProps {
  sessionId: string;
}

export default function ShoppingCart({ sessionId }: ShoppingCartProps) {
  const [isOpen, setIsOpen] = useState(false);
  const { cartItems, totalItems, refreshCart, isLoading } = useCart();

  const handleRemoveItem = async (itemId: number) => {
    try {
      await removeFromCart(itemId);
      await refreshCart();
    } catch (error) {
      alert('Failed to remove item from cart');
    }
  };

  const totalPrice = cartItems.reduce(
    (sum, item) => sum + item.product.price * item.quantity,
    0
  );

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition-colors"
      >
        <svg
          className="w-5 h-5"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M3 3h2l.4 2M7 13h10l4-8H5.4m0 0L7 13m0 0l-1.5 6h9M17 13v6a2 2 0 01-2 2H9a2 2 0 01-2-2v-6"
          />
        </svg>
        <span>Cart ({totalItems})</span>
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-96 bg-white rounded-lg shadow-xl z-50 border">
          <div className="p-4 border-b">
            <h3 className="font-semibold text-lg">Shopping Cart</h3>
          </div>

          <div className="max-h-96 overflow-y-auto">
            {isLoading ? (
              <div className="p-4 text-center">Loading cart...</div>
            ) : cartItems.length === 0 ? (
              <div className="p-4 text-center text-gray-500">
                Your cart is empty
              </div>
            ) : (
              <div className="p-4">
                {cartItems.map((item) => (
                  <div
                    key={item.id}
                    className="flex items-center justify-between py-2 border-b"
                  >
                    <div className="flex-1">
                      <h4 className="font-medium">{item.product.name}</h4>
                      <p className="text-sm text-gray-600">
                        ${item.product.price} x {item.quantity}
                      </p>
                    </div>
                    <button
                      onClick={() => handleRemoveItem(item.id)}
                      className="text-red-500 hover:text-red-700 ml-2"
                    >
                      <svg
                        className="w-5 h-5"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                        />
                      </svg>
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {cartItems.length > 0 && (
            <div className="p-4 border-t bg-gray-50">
              <div className="flex justify-between items-center mb-2">
                <span className="font-semibold">Total:</span>
                <span className="font-bold text-lg">${totalPrice.toFixed(2)}</span>
              </div>
              <a
                href="/checkout"
                className="block w-full bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 text-center"
              >
                Checkout
              </a>
            </div>
          )}
        </div>
      )}
    </div>
  );
}